import 'dart:async';
import 'dart:io';

import 'package:get/get.dart';
import 'package:permission/permission.dart';

import '../utils/utils.dart';

mixin PermissionHandler{

  StreamSubscription? _adapterStateSubs;
  void initPermissionHandler({bool enableLog = false}){
    Log.enableLog = enableLog;
    _adapterStateSubs = Permission.adapterState.listen(_onAdapterState);
  }

  Stream<bool> get adapterState => Permission.adapterState;

  bool _isBleOn = false;
  /// 蓝牙适配器状态回调
  void _onAdapterState(bool status){
    Log.log('_onAdapterState $status');
    _isBleOn = status;
  }

  /// 检查当前蓝牙状态
  Future<bool> checkBleStatus() async{
    if(!_isBleOn){
      return (await Utils.openBle()).compareTo("true") == 0;
    }
    return _isBleOn;
  }

  Future<void> closePermissionHandler() async{
    _adapterStateSubs?.cancel();
  }

  //|///////////// 权限相关 //////////////

  List<Permissions> _bleAndroidNew = [
    Permissions.bluetoothScan,
    Permissions.bluetoothConnect
  ];
  List<Permissions> _bleAndroidOld = [
    Permissions.location,
    Permissions.bluetoothScan,
    Permissions.bluetoothConnect
  ];
  List<Permissions> _bleIos = [
    Permissions.bluetooth,
  ];
  bool _bleInit = false;

  /// 检查所需权限
  Future<void> _checkBlePermissions() async{
    List<Permissions> bleAndroid = [];
    if(Platform.isAndroid){
      bleAndroid = (await DeviceInfoUtil.instance.androidInfo).version.sdkInt > 30
          ? _bleAndroidNew
          : _bleAndroidOld;
    }

    await PermissionUtil.checkPermissions(Platform.isIOS ? _bleIos : bleAndroid, 'ble_needed'.tr).then((value) {
      if(value){
        if(!_bleInit){
          _bleInit = true;
        }
      }
    });
  }

  /// 检查权限是否初始化了
  Future<bool> checkBlePermissionInit() async{
    bool flag = _bleInit;
    if(!_bleInit){
      List<Permissions> bleAndroid;
      if(Platform.isAndroid){
        bleAndroid =
        (await DeviceInfoUtil.instance.androidInfo).version.sdkInt > 30
            ? _bleAndroidNew
            : _bleAndroidOld;
      }else{
        bleAndroid = [];
      }

      if(await PermissionUtil.checkPermissionsStatus(Platform.isIOS ? _bleIos : bleAndroid)){
        _bleInit = true;
        flag = true;
      }else{
        await _checkBlePermissions();
        flag = _bleInit;
      }
    }
    return flag;
  }
}